package org.duoyi.striver.service.task;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.duoyi.striver.StriverApplication;
import org.duoyi.striver.consts.Area;
import org.duoyi.striver.consts.Picture;
import org.duoyi.striver.consts.Shortcuts;
import org.duoyi.striver.consts.TaskState;
import org.duoyi.striver.model.Point;
import org.duoyi.striver.model.impl.Sleeper;

import java.util.ArrayList;
import java.util.List;

/**
 * 挖宝图
 */
@Slf4j
public class DigTreasureTask extends AbstractTask {

    private static final List<Area> PAGES = new ArrayList<>(4);

    static {
        PAGES.add(Area.背包_第一页);
        PAGES.add(Area.背包_第二页);
        PAGES.add(Area.背包_第三页);
        PAGES.add(Area.背包_第四页);
    }


    @Override
    public void doTask() {
        before();
        if (this.state.equals(TaskState.FINISHED)) {
            return;
        }
        int count = 0;
        int times = 0;
        while (times < 15) {
            Sleeper.sleep(4000);
            synchronized (StriverApplication.class) {
                if (Picture.挖图_宝图.find()) {
                    log.info("挖图-第{}张", ++count);
                    Area.挖图_使用.leftClick();
                    times = 0;
                    continue;
                }
            }
            times++;
        }
    }

    private void before() {
        synchronized (StriverApplication.class) {
            while (!Picture.背包_标识.find()) {
                log.info("打开背包");
                Shortcuts.打开背包.press();
            }
            TaskState state = TaskState.FINISHED;
            Point point = null;
            Point select = null;

            for (Area page : PAGES) {
                log.info("打开背包" + page.name().split("_")[1]);
                page.leftClick();
                point = Picture.背包_宝图.findPoint();
                if (point != null) {
                    log.info("选择宝图");
                    point.leftClick();
                    while ((select = Picture.背包_宝图选择.findPoint()) == null) {
                        point.leftClick();
                    }
                    select.addR(RandomUtil.randomInt(200, 300), RandomUtil.randomInt(0, 30));
                    log.info("使用宝图");
                    select.leftClick();
                    state = TaskState.RUNNING;
                    Shortcuts.Esc.press();
                    break;
                }
            }

            this.state = state;
        }
    }
}
